﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Serilog;
using System;

//using Serilog.Sinks.RabbitMQ;

namespace PasteTimer
{
    /// <summary>
    /// 
    /// </summary>
    public class Program
    {

        /// <summary>
        /// 
        /// </summary>
        public static IConfiguration Configuration { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static int Main(string[] args)
        {

            Configuration = new ConfigurationBuilder()
                    .SetBasePath(System.IO.Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    .AddEnvironmentVariables()
                    .Build();


            Log.Logger = new LoggerConfiguration()
                //.MinimumLevel.Information()
                //.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                //.WriteTo.Console()
                .ReadFrom.Configuration(Configuration)
                //.WriteTo.File(Path.Combine("Logs", @"log.txt"), rollingInterval: RollingInterval.Day, retainedFileCountLimit: 60, fileSizeLimitBytes: 3145728, rollOnFileSizeLimit: true)
                .Enrich.FromLogContext()
                .CreateLogger();

            //if(Configuration.GetSection("TaskConfig:PassWord"))


            var publictoken = Configuration.GetValue<string>("TaskConfig:PublicToken");
            var boolsingle = Configuration.GetValue<Boolean>("TaskConfig:SingleModel");
            if (!String.IsNullOrEmpty(publictoken))
            {
                if (publictoken == "888888888888" && !boolsingle)
                {
                    throw new Exception("System Slave Token Error! you can run docker by -e \"TaskConfig:PublicToken={系统密钥}\"");
                }
            }
            try
            {
                Log.Information("Starting web host.");
                CreateHostBuilder(args).Build().Run();
                return 0;
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly!");
                return 1;
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        internal static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
            .UseSerilog()
            .UseAutofac();
    }
}
